package com.ocm.commerceinteraction.ui;


import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.MainActivity;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.GroupDetail;
import com.ocm.commerceinteraction.ui.adapter.GroupListViewAdapter;
import com.ocm.commerceinteraction.util.MethedUtil;
import com.ocm.commerceinteraction.util.helper.DBHelper;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.helper.NotifyUtil;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;
import com.ocm.commerceinteraction.util.loading.Loading;
import com.ocm.commerceinteraction.util.view.MyAlertDialog;
import com.ocm.commerceinteraction.util.view.SearchEditText;
import com.ocm.commerceinteraction.util.view.percentsupport.PercentRelativeLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.EditorAction;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.util.List;
import java.util.Random;

import easeui.EaseConstant;
import easeui.controller.EaseUI;
import easeui.domain.EaseUser;

import static com.easemob.EMNotifierEvent.Event.EventNewMessage;
import static com.ocm.commerceinteraction.GlobalApplication.context;


@EFragment(R.layout.fragment_home)
public class HomeFragment extends BaseFragment   implements EMEventListener {

    GroupListViewAdapter groupListViewAdapter;//我的群

    @ViewById(R.id.toptitle_title)
    TextView topTitle;
    @ViewById(R.id.saveBtn)
    ImageView saveBtn;

    HomeFragment homeFragment;
    @ViewById(R.id.back_btn)
    PercentRelativeLayout backBtn;
    @ViewById(R.id.list)
    ListView userGourplist;
//    @ViewById(R.id.tuijianList)
//    ListView tjGourpList;
    @ViewById(R.id.search)
    SearchEditText searchEditText;
//    @ViewById(R.id.tip)
//    TextView tip;

    @ViewById(R.id.tv_group_annouce)
    TextView groupAnnouce;

    @FragmentArg("group_uniq_id")
    String group_uniq_id;
    private static final String TAG = "HomeFragment";

    @AfterViews
    @Override
    void initView() {
        homeFragment = this;
        topTitle.setText("商业互动");
        backBtn.setVisibility(View.GONE);
        saveBtn.setVisibility(View.VISIBLE);
        saveBtn.setImageDrawable(this.getActivity().getResources().getDrawable(R.drawable.creat_qun));
        loadData("");
    }

    @EditorAction(R.id.search)
    boolean editorActionListenerOnSearch(TextView v, int actionId, KeyEvent event){
        {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    /*隐藏软键盘*/
                InputMethodManager imm = (InputMethodManager) v
                        .getContext().getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(
                            v.getApplicationWindowToken(), 0);
                }
                if(v.getText().toString().trim().length()<1){
                    loadData("");
                }else{
                    loadData(v.getText().toString().trim());
                }
                return true;
            }
            return false;
        }
    }

    //加载数据
    public void loadData(final String param) {
            Loading.getInstance(getActivity()).startLoading();
            //加载我的群列表
            if(param==null||"".equals(param)){
                requestUrl = RequestAddr.userGroupAddr;
            }else{
                requestUrl = RequestAddr.searchUserGroupAddr.replace("$keywords",param);
//                tip.setVisibility(View.GONE);
            }
            if (GlobalApplication.localCookie != null) {
                GlobalApplication.xtHttp.configCookieStore(GlobalApplication.localCookie);
            }
            GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);
                    Loading.stopLoading();
                    dealDataUser(o,param);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    Loading.stopLoading();
                }
            });
    }


    /*推荐群*/
    private void dealData(Object object,String param) {
        try {
            GroupDetail   tjgroupDetail=  gson.fromJson(object.toString(), GroupDetail.class);
            if(param==null||param.equals("")){
                if(tjgroupDetail.getData().size()>0){
//                    tjgroupDetail.getData().get(0).setFlag(1);
//                    List<GroupDetail.DataEntity> temp=userGroupDetail.getData();
//                    temp.addAll(tjgroupDetail.getData());
                    if(userGroupDetail.getData().size()>0){
                        userGroupDetail.getData().get(0).setFlag(1);
                        List<GroupDetail.DataEntity> temp=tjgroupDetail.getData();
                        temp.addAll(userGroupDetail.getData());
                        userGroupDetail.setData(temp);
                    }
                }
            }
            groupListViewAdapter.notifyDataSetChanged();
        } catch (JsonSyntaxException e) {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
    }

    //我的群处理数据
    public GroupDetail userGroupDetail;

    private void dealDataUser(Object object, final String param) {
        userGroupDetail = new GroupDetail();
        try {
            userGroupDetail = gson.fromJson(object.toString(), GroupDetail.class);
        } catch (JsonSyntaxException e) {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
        groupListViewAdapter = new GroupListViewAdapter(getActivity(), userGroupDetail);
        userGourplist.setAdapter(groupListViewAdapter);

        GlobalApplication.userGroupDetail = userGroupDetail;

        //加载推荐列表
        requestUrl = RequestAddr.recommendGroupAddr;
        if (GlobalApplication.localCookie != null) {
            GlobalApplication.xtHttp.configCookieStore(GlobalApplication.localCookie);
        }
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o,param);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });


        GlobalApplication.userInfoList = DBHelper.getFriendlist();
        //get easeui instance
        GlobalApplication.easeUI = EaseUI.getInstance();
////需要easeui库显示用户头像和昵称设置此provider
        GlobalApplication.easeUI.setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {

            @Override
            public EaseUser getUser(String username) {
                return getUserInfo(username);
            }
        });

    }


//    EaseUser getUserInfo(String username) {
//        EaseUser easeUser;
//        for (int i = 0; i < userGroupDetail.getData().size(); i++) {
//            if (userGroupDetail.getData().get(i).getGroupname().equals(username)) {
//                easeUser = new EaseUser(userGroupDetail.getData().get(i).getGroupname());
//                easeUser.setUsername(userGroupDetail.getData().get(i).getGroupname());
//                easeUser.setNick(userGroupDetail.getData().get(i).getGroupname());
//                easeUser.setAvatar(RequestAddr.baseUrl + userGroupDetail.getData().get(i).getIcon());
//                return easeUser;
//            }
//        }
//        return null;
//    }
private EaseUser getUserInfo(String username) {
    //获取user信息，demo是从内存的好友列表里获取，
    //实际开发中，可能还需要从服务器获取用户信息,
    //从服务器获取的数据，最好缓存起来，避免频繁的网络请求
    EaseUser easeUser = null;
    if (username.equals(GlobalApplication.loginModel.getData().getUser_uniq_id())) {
        easeUser = new EaseUser(username);
        easeUser.setAvatar(RequestAddr.baseUrl + GlobalApplication.loginModel.getData().getIcon());
        easeUser.setUsername(GlobalApplication.loginModel.getData().getUser_uniq_id());
        easeUser.setSelect(false);
        easeUser.setEid(GlobalApplication.loginModel.getData().getUser_uniq_id());
        easeUser.setNick(GlobalApplication.loginModel.getData().getNick());
        return easeUser;
    }
    for (int i = 0; i < GlobalApplication.userInfoList.size(); i++) {
        if (username.equals(GlobalApplication.userInfoList.get(i).getUser_uniq_id())) {
            easeUser = new EaseUser(GlobalApplication.userInfoList.get(i).getUser_uniq_id());
            easeUser.setAvatar(RequestAddr.baseUrl + GlobalApplication.userInfoList.get(i).getIcon());
            easeUser.setUsername(GlobalApplication.userInfoList.get(i).getUser_uniq_id());
            easeUser.setSelect(false);
            easeUser.setEid(GlobalApplication.userInfoList.get(i).getUser_uniq_id());
            easeUser.setNick(GlobalApplication.userInfoList.get(i).getNick());
        }
    }

    return easeUser;
}
    @ItemClick(R.id.list)
    void userOnItemClick(int position) {

        if(userGroupDetail.getData().get(position).getIs_join().equals("2")){// 推荐群列表
            showEditDiallog(userGroupDetail.getData().get(position).getGroup_uniq_id()+"");
            return;
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
        bundle.putString(EaseConstant.EXTRA_USER_ID, userGroupDetail.getData().get(position).getHuanxing_groupid() + "");
        bundle.putString("name", userGroupDetail.getData().get(position).getGroupname() + "");
        bundle.putString("groupUniqId", userGroupDetail.getData().get(position).getGroup_uniq_id() + "");
        bundle.putString("notice", "公告: "+userGroupDetail.getData().get(position).getNotice());
        bundle.putString("is_block", userGroupDetail.getData().get(position).getIs_block());
        GlobalApplication.unReadListGroup.remove(userGroupDetail.getData().get(position).getHuanxing_groupid());
        intent.setClass(getActivity(), ChatActivity.class);
        intent.putExtras(bundle);
        startActivityForResult(intent, 001);
    }

    /**
     * 用户主动请求加入某群
     *
     * @param group_uniq_id 群id
     */

    private void requestJoinGroup(String group_uniq_id,String msg) {
        requestUrl = RequestAddr.requestJoin + "group_uniq_id/" + group_uniq_id+"/msg/"+msg;
        if (GlobalApplication.localCookie != null) {
            xtHttp.configCookieStore(GlobalApplication.localCookie);
        }
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealBaseData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }


    @Override()
    @Click({R.id.saveBtn})
    void Click(View view) {
        switch (view.getId()) {
            case R.id.saveBtn:
                Intent intent = new Intent();
                intent.setClass(MainActivity.getInstance(), CreatChatRoomActivity_.class);
                MainActivity.getInstance().startActivity(intent);
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 001 && resultCode == 002 && data != null) {
            if (data.getExtras().getBoolean("dataChange")) {
                loadData("");
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    MyAlertDialog joinGroupDialog;

    void showEditDiallog(final String group_uniq_id) {
        joinGroupDialog = new MyAlertDialog(getActivity());
        joinGroupDialog.setTitle("入群申请");
        joinGroupDialog.setMessage("");
        joinGroupDialog.setNegativeButton("   确定    ", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                joinGroupDialog.dismiss();
                requestJoinGroup(group_uniq_id,joinGroupDialog.getMessage());
            }
        });

        joinGroupDialog.setPositiveButton("", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                joinGroupDialog.dismiss();
            }
        });
    }




    public void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除

        listView.setLayoutParams(params);
    }

    @Override
    public void onResume() {
        super.onResume();
        EaseUI.getInstance().pushActivity(getActivity());
        // register the event listener when enter the foreground
        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{EventNewMessage});
    }

    NotifyUtil notifyUtil;
    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
            case EventNewMessage:
                // 获取到message
                EMMessage message = (EMMessage) event.getData();
                String username = null;
                // 群组消息
                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                    username = message.getTo();
                } else {
                    // 单聊消息
                    username = message.getFrom();
                }
                // 如果消息不是和当前聊天ID的消息
                LogHelper.i(message.getFrom()+",getTo"+ message.getTo());


//                    EaseUI.getInstance().getNotifier().onNewMsg(message);
                notifyUtil = new NotifyUtil(context, 1);
                Random random = new Random(System.currentTimeMillis());
                PendingIntent contentIntent = PendingIntent.getActivity(context,
                        random.nextInt(), new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
                String Title1 = "";
                if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                    for (int i = 0; i < userGroupDetail.getData().size(); i++) {
                        if (userGroupDetail.getData().get(i).getHuanxing_groupid().equals(message.getTo())){
                            Title1 = userGroupDetail.getData().get(i).getGroupname();
                        }
                    }
                } else {
                    for (int i = 0; i < GlobalApplication.userInfoList.size(); i++) {
                        if (GlobalApplication.userInfoList.get(i).getUser_uniq_id().equals(message.getFrom())) {
                            Title1 = GlobalApplication.userInfoList.get(i).getNick();
                        }
                    }
                }
                notifyUtil.notify_normal_singline(contentIntent, R.mipmap.logo, "", Title1, "发来新消息", true, true, true);
                if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                    username = message.getTo();
                    if (GlobalApplication.unReadListGroup.get(message.getTo()) != null) {
                        int numGroup = GlobalApplication.unReadListGroup.get(message.getTo());
                        GlobalApplication.unReadListGroup.put(message.getTo(), ++numGroup);
                    } else {
                        GlobalApplication.unReadListGroup.put(message.getTo(), 1);
                    }
                    groupListViewAdapter.notifyDataSetChanged();
                    userGourplist.invalidate();
                } else if (message.getChatType() == EMMessage.ChatType.Chat) {
                    if (GlobalApplication.unReadListFri.get(message.getFrom()) != null) {
                        int numFri = GlobalApplication.unReadListFri.get(message.getFrom());
                        GlobalApplication.unReadListFri.put(message.getFrom(), ++numFri);
                    } else {
                        GlobalApplication.unReadListFri.put(message.getFrom(), 1);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onPause() {
        super.onDestroy();
        EMChatManager.getInstance().unregisterEventListener(this);

        // 把此activity 从foreground activity 列表里移除
//        EaseUI.getInstance().popActivity(getActivity());
    }
}


